﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using System.Data.Sql;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using QuoteTree;
using System.Collections;

public partial class TreeAnalysis : System.Web.UI.Page
{
    protected void Page_Load(object sender, System.EventArgs e)
    {
        this.Table5.Visible = this.CheckBox4.Checked;

        if (Session.IsNewSession)
        {
            // If it says it is a new session, but an existing cookie exists, then it must 
            // have timed out (can't use the cookie collection because even on first 
            // request it already contains the cookie (request and response
            // seem to share the collection)
            string szCookieHeader = Request.Headers["Cookie"];
            if ((null != szCookieHeader) && (szCookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
            {
                Response.Redirect("sessionTimeout.htm");
            }
        }
        string ddl_value = "";

        if (!this.Request.Browser.IsBrowser("IE") && !this.Request.Browser.IsBrowser("opera")) this.DropDownList1.Visible = false;

        if (!IsPostBack)
        {
            //Remove previous tree
            this.Session["tree"] = null;
            this.Session["leftframe"] = null;

            //Read product names from dir just once and store it in a session variable.
            string[] dirs = Directory.GetDirectories(Server.MapPath("Private/Quotes/company_test"));
            string[] temp;
            for (int i = 0; i < dirs.Length; i++)
            {
                temp = dirs[i].Split("\\".ToCharArray());
                dirs[i] = temp[temp.Length - 1];
            }
            this.Session["dirs"] = dirs;

            //this.RssFeed1.DataSource = "http://www.quotationspage.com/data/mqotd.rss";
            //this.RssFeed1.DataBind();

            string ID = "";
            string quote = "";

            //this.Session.Timeout = 480;
            DataSet ds;
            if (this.Request.QueryString["quote"] != null)
            {
                quote = this.Request.QueryString["quote"].ToString();
                BinaryFormatter formater = new BinaryFormatter();
                byte[] bytes_stream;
                ds = qman.DataHelp.DataAccess.getDataSet("select quote,cmp_id from adtech_quotes where id=" + this.Request.QueryString["quote"].ToString());
                bytes_stream = ds.Tables[0].Rows[0][0] as byte[];
                ID = ds.Tables[0].Rows[0][1].ToString();
                MemoryStream memory_stream = new MemoryStream(bytes_stream);
                QTree tree = (formater.Deserialize(memory_stream)) as QTree;
                this.Session["tree"] = tree;
                this.IFrame1.Attributes.Add("Src", "Quotes/" + tree.Root.GetPath() + "/homepage.htm");
                this.DropDownList1.Enabled = false;
                ddl_value = tree.Root.name;
                this.Button2_Click1(this, null);
            }
            else if (this.Request.QueryString["cmp_id"] != null)
            {
                ID = this.Request.QueryString["cmp_id"].ToString();
            }

            DataSet ds1 = qman.DataHelp.DataAccess.getDataSet("select name from companies where id='" + ID + "'");

            //this.HyperLink1.Text = ds1.Tables[0].Rows[0][0].ToString().ToUpper();
            //this.HyperLink1.NavigateUrl = "customer_details.aspx?id=" + ID;
            this.HyperLink6.NavigateUrl = "QuoteTreeDetails.aspx?cmp_id=" + ID + "&quote=" + quote;
            this.HyperLink6.Target = "details";

            //If it is a revision disable the tree and other controls
            if (this.Request.QueryString["quote"] != null && this.Request.QueryString["quote"].ToString() != ""
                        && (this.Request.QueryString["revision"] == null || this.Request.QueryString["revision"] != "yes"))
            {
                this.TreeView1.Enabled = false;
                //this.HyperLink6.Enabled = false;
                //this.Button3.Visible = true;
            }

        }
        else
        {
            this.RetrieveExpandedCollapsedInfo(this.TreeView1);
            ddl_value = this.DropDownList1.SelectedValue;
            this.Page.Title = ddl_value;

            if (this.Session["leftframe"] != null && this.Session["leftframe"].ToString() != "")
                this.IFrame1.Attributes.Add("src", this.Session["leftframe"].ToString());
            else this.IFrame1.Attributes.Add("src", "success.aspx");
        }



        this.DropDownList1.DataSource = this.Session["dirs"] as string[];
        this.DropDownList1.DataBind();
        if (this.DropDownList1.Items[0].Value != "") this.DropDownList1.Items.Insert(0, "");
        if (this.DropDownList1.Items.FindByText(ddl_value) != null)
            this.DropDownList1.SelectedValue = ddl_value;
    }


    //	public void SaveExpandedCollapsedInfo(TreeView tree)
    //	{
    //		this.Session["treeinfo"] = tree;
    //	}

    public void RetrieveExpandedCollapsedInfo(TreeView tview)
    {
        if (tview != null && tview.Nodes.Count > 0 && tview.Nodes[0].ChildNodes.Count > 0)
        {
            QTree tree = this.Session["tree"] as QTree;
            if (tree != null)
            {
                RetrieveExpandedCollapsedInfo(tview.Nodes[0].ChildNodes[0], tree);
                this.Session["tree"] = tree;
            }
        }
    }
    public void RetrieveExpandedCollapsedInfo(TreeNode source, QTree destination)
    {

        if (destination.GetNodeFromPath(source.ValuePath.Replace("Quote/", "")) != null)
        {
            if (source.Expanded == null) destination.GetNodeFromPath(source.ValuePath.Replace("Quote/", "")).expanded = false;
            else
                destination.GetNodeFromPath(source.ValuePath.Replace("Quote/", "")).expanded = source.Expanded.Value;
            //this.Response.Write(source.Expanded);

            for (int i = 0; i < source.ChildNodes.Count; i++)
                RetrieveExpandedCollapsedInfo(source.ChildNodes[i], destination);
        }
    }


    #region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
        //
        // CODEGEN: This call is required by the ASP.NET Web Form Designer.
        //
        InitializeComponent();
        base.OnInit(e);
    }

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {

    }
    #endregion
    protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
    {

    }

    public void FillTreeViewNode(INode node, TreeNode ui_node)
    {
        decimal o;
        if (node.hidden && !this.CheckBox3.Checked) return;
        if (node.parent != null && node.parent.parent != null && node.parent.parent.type == NodeType.decision && !node.parent.selected) return;
        if (node.parent != null && node.parent.type == NodeType.math && (node.parent as MathNode).edit_children &&
            decimal.TryParse((node as MathNode).formula, out o)) return;
        
        if (node.parent != null && node.parent.optional && !node.parent.selected) return;
        

        string name = node.name;

        TreeNode new_node = new TreeNode();
        //new_node.SelectAction = TreeNodeSelectAction.SelectExpand;
        decimal output;
        //if (node.type == NodeType.product) { name += " $" + (node as ProductNode).price; if ((node.parent as DecisionNode).is_user_decision) new_node.ShowCheckBox = true; }
        if (node.type == NodeType.math)
        {
            if ((node as MathNode).edit_children)
            {
                name += " (";
                foreach (INode child in node.children)
                {
                    if (!child.hidden)
                        name += child.total() + " " + child.units + ", ";
                }
                name = name.TrimEnd(" ".ToCharArray());
                name = name.TrimEnd(",".ToCharArray());
                name += ")";

            }
            else
                if (Decimal.TryParse((node as MathNode).formula, out output)) name += ": " + (node as MathNode).formula + " " + node.units;
                else
                    //Show formulas if not a fixed number
                    if (this.CheckBox1.Checked) name += " [" + (node as MathNode).formula + "]";
            new_node.ShowCheckBox = (node as MathNode).optional;
            //name += " report=" + node.report;
        }

        if (node.type == NodeType.sumset)
        {

            if (this.CheckBox2.Checked) name += ": " + (node as SumSetNode).total() + " " + node.units;
            new_node.ShowCheckBox = (node as SumSetNode).optional;
        }


        if (node.type == NodeType.range)
        {
            //Show formulas
            if (this.CheckBox1.Checked) name += " [" + (node as RangeNode).range + "]";
            new_node.ShowCheckBox = (node as RangeNode).optional;
        }

        if (node.type == NodeType.conditional)
        {
            //Show formulas
            if (this.CheckBox1.Checked) name += " [" + (node as ConditionalNode).formula + "]";
            new_node.ShowCheckBox = (node as ConditionalNode).optional;
        }

        if (node.type == NodeType.conditionalrules)
        {
            //Show formulas
            if (this.CheckBox1.Checked) name += " [" + (node as ConditionalRulesNode).expression + "]";
            new_node.ShowCheckBox = (node as ConditionalRulesNode).optional;
        }

        //Show subtotals if not a fixed number
        if (this.CheckBox2.Checked)
        {
            if (!(node.type == NodeType.math && decimal.TryParse((node as MathNode).formula, out output)))
            {
                if (node.units.Trim() == "$") name += " = [" + node.units + Decimal.Round(node.total(), 2) + "]";
                else name += " = [" + Decimal.Round(node.total(), 2) + " " + node.units + "]";
            }
        }

        if (node.selected)
        {
            new_node.Checked = true;
            //if (new_node.ShowCheckBox)
            {
                try
                {
                    if (node != null)
                    {
                        if (!node.IsComplete())
                            new_node.ImageUrl = "~/images/4anidot1a.gif";
                        //else new_node.ImageUrl = "1dot1a.gif";
                        if (node.hidden)
                            new_node.ImageUrl = "h.gif";
                    }
                }
                catch (Exception) { }
            }

        }
        if (node.type == NodeType.decision && node.parent != null && ((node as DecisionNode).optional || node.parent.type == NodeType.decision)) new_node.ShowCheckBox = true;
        if (node.expanded) new_node.Expanded = true;

        new_node.Text = name;
        new_node.Value = node.name;
        //new_node.ToolTip = "Here is going to be the description for this item.";
        new_node.ToolTip = node.description;

        //To know if the node is a fixed value or a formula
        if (node.read_only || node.type == NodeType.product) { }
        else
        {
            if (node.type == NodeType.math)
            {
                decimal flag;
                if (decimal.TryParse((node as MathNode).formula, out flag) || (node as MathNode).edit_children)
                    new_node.NavigateUrl = "ChangeTreeValue.aspx" + "?node=" + node.GetPath();
                else new_node.NavigateUrl = "Quotes/" + node.GetPath().Replace('\\', '/') + "/homepage.htm";
            }
            else
                if (node.type == NodeType.sumset)
                { new_node.NavigateUrl = "AppendNodes.aspx" + "?node=" + node.GetPath(); }
                else new_node.NavigateUrl = "Quotes/" + node.GetPath().Replace('\\', '/') + "/homepage.htm";
            new_node.Target = "details";
        }
        //If not selected and some brother is selected then not insert the node.
        bool some_selected = false;
        if (node.parent != null && node.parent.type == NodeType.decision && !node.selected)
        {
            foreach (INode n in node.parent.children)
                if (n.selected) some_selected = true;
            if (some_selected) return;
        }

        ui_node.ChildNodes.Add(new_node);
        if (node.children != null && node.children.Count != 0)
        {
            foreach (INode n in node.children)
            {
                FillTreeViewNode(n, new_node);
            }
        }


    }

    /*public void FillAlternativeView()
    {
        QTree tree;
        tree = this.Session["tree"] as QTree;
		
        bool is_selected = false;
        if (tree.Root.type == NodeType.decision)
        {
            INode selected_child = null;
            foreach (INode n in tree.Root.children)
                if (n.selected) { is_selected = true; selected_child = n; break; }
            if (is_selected) DrawOptions(selected_child);
        }
        else DrawOptions(tree.Root);
 
    }

    public void DrawOptions(INode n)
    {
			
        if (n != null)
        {

            if (n.parent !=null && n.parent.type == NodeType.math && ((n.type == NodeType.math && (n as MathNode).optional) || (n.type == NodeType.decision && !n.selected && (n as DecisionNode).optional)))
                {
                    Label lb = new Label();
                    lb.Text = n.name;
                    this.TD2.Controls.Add(lb);
                    Label separator = new Label();
                    separator.Text = "------";
                    this.TD2.Controls.Add(separator);

                }
                else
                    if (n.parent != null && n.parent.type == NodeType.decision && ((n.type == NodeType.math && (n as MathNode).optional) || n.type == NodeType.decision && !n.selected))
                    {
                        Label lb = new Label();
                        lb.Text = n.name;
                        this.TD3.Controls.Add(lb);
                        Label separator = new Label();
                        separator.Text = "------";
                        this.TD3.Controls.Add(separator);
                    }


            if (n.children != null)
                foreach (INode c in n.children)
                    if (c != null) DrawOptions(c);
        }
        else return;
    }
*/
    protected void TreeView1_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e)
    {
        //this.Response.Write("Function TreeView1_TreeNodeCheckChanged");
        if (this.Session["tree"] != null)
        {

            QTree tree;

            tree = this.Session["tree"] as QTree;
            INode tmp = tree.GetNodeFromPath(e.Node.ValuePath.Replace("Quote/", ""));
            if (tmp != null)
            {
                tmp.selected = tmp.expanded = e.Node.Checked;

            }
            if (e.Node.Checked && e.Node.Parent != null)
            {
                INode parent = tree.GetNodeFromPath(e.Node.ValuePath.Replace("Quote/", "")).parent;
                if (parent.type == NodeType.decision)
                {
                    foreach (INode n in parent.children)
                    {
                        if (n.name != e.Node.Value) n.selected = false;
                    }

                }
            }

            this.Session["tree"] = tree;
            //this.Label1.Text = "Press Calculate button";

            if (e.Node.Checked)
            {
                if (tmp.type == NodeType.math)
                {
                    decimal res;
                    if (decimal.TryParse((tmp as MathNode).formula, out res)) this.IFrame1.Attributes.Add("Src", "ChangeTreeValue.aspx?node=" + e.Node.ValuePath.Replace("Quote/", "").Replace("/", "\\"));
                    else this.IFrame1.Attributes.Add("Src", "Quotes/" + e.Node.ValuePath.Replace("Quote/", "") + "/homepage.htm");

                }
                else
                    this.IFrame1.Attributes.Add("Src", "Quotes/" + e.Node.ValuePath.Replace("Quote/", "") + "/homepage.htm");
            }
            else this.IFrame1.Attributes.Add("Src", "Quotes/" + e.Node.Parent.ValuePath.Replace("Quote/", "") + "/homepage.htm");


            this.Button2_Click1(this, null);

            //To set the nodes images
            try
            {
                if (e.Node.Checked)
                {
                    if (tmp != null)
                    {
                        if (!tmp.IsComplete())
                            this.TreeView1.FindNode(e.Node.ValuePath).ImageUrl = "~/images/4anidot1a.gif";

                        if (tmp.hidden)
                            this.TreeView1.FindNode(e.Node.ValuePath).ImageUrl = "h.gif";
                    }

                }
                else this.TreeView1.FindNode(e.Node.ValuePath).ImageUrl = "";
            }
            catch (Exception ex) { this.Response.Write(ex.Message); }

        }
        else
        {
            string[] dirs = Directory.GetDirectories(Server.MapPath("Quotes"));
            this.DropDownList1.DataSource = dirs;
            this.DropDownList1.DataBind();
            this.DropDownList1.Items.Insert(0, "");

        }



    }

    protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
    {

    }


    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {

        this.TreeView1.Nodes.Clear();
        this.IFrame1.Attributes.Add("src", "quotes/homepage.htm");

        if (this.DropDownList1.SelectedItem.Text != "")
        {
            // Check if there's a tree cached in an application variable and set it as a session variable
            if (this.Application["alltrees"] != null)
            {
                ArrayList alltrees = this.Application["alltrees"] as ArrayList;
                QTree tree;
                foreach (QTree t in alltrees)
                {
                    if (t.Root.name == this.DropDownList1.SelectedItem.Text)
                    {
                        //Free the memory
                        QTree delete = (this.Session["tree"] as QTree);
                        delete = null;
                        System.GC.Collect();
                        //Assign new tree
                        this.Session["tree"] = new QTree(t);
                        break;
                    }
                }
            }
            else
            {
                string s = Server.MapPath("Private/Quotes/company_test") + "\\" + this.DropDownList1.SelectedItem.Text;
                this.Session["tree"] = new QTree(@s);
            }

            TreeNode root = new TreeNode("Quote");
            string ID = "";
            if (this.Request.QueryString["cmp_id"] != null) ID = this.Request.QueryString["cmp_id"].ToString();
            root.NavigateUrl = "QuoteTreeDetails.aspx?cmp_id=" + ID;
            root.Target = "details";
            this.FillTreeViewNode((this.Session["tree"] as QTree).Root, root);
            this.TreeView1.Nodes.Add(root);
            this.TreeView1.Nodes[0].Expanded = true;
            //this.FillAlternativeView();
            if (this.DropDownList1.SelectedIndex != 0)
            {
                //this.Page.Title = this.DropDownList1.SelectedItem.Text;
                this.IFrame1.Attributes.Add("Src", "quotes/" + this.DropDownList1.SelectedItem.Text + "/" + "homepage.htm");
            }
            this.Session["leftframe"] = null;

        }
        else
        {
            //Free the memory
            QTree delete = (this.Session["tree"] as QTree);
            delete = null;
            System.GC.Collect();
        }
        this.Label1.Text = "Total = ";

    }

    protected void Button2_Click1(object sender, EventArgs e)
    {
        if (this.Session["tree"] != null)
        {
            try
            {
                QTree tree = this.Session["tree"] as QTree;

                this.TreeView1.Nodes.Clear();
                TreeNode root = new TreeNode("Quote");
                string ID = "";
                if (this.Request.QueryString["cmp_id"] != null) ID = this.Request.QueryString["cmp_id"].ToString();
                root.NavigateUrl = "javascript:;";

                this.FillTreeViewNode(tree.Root, root);
                this.TreeView1.Nodes.Add(root);

                // XmlDataSource xml = new XmlDataSource();
                // xml.Data = tree.GetXML();
                //this.TreeView1.DataSource = xml;
                //this.TreeView1.DataBind();
                //this.Response.Write(tree.GetXML());

                this.TreeView1.Nodes[0].Expanded = true;
                this.Label1.Text = "Total= $" + Decimal.Round(tree.Root.total(), 2);

            }
            catch (Exception) { }
        }
    }

    protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
    {
        this.Session["leftframe"] = "";
        this.Button2_Click1(this, null);
    }

    protected void Button3_Click(object sender, EventArgs e)
    {

        this.TreeView1.Enabled = true;
        this.HyperLink6.Enabled = true;
        //this.Button3.Visible = false;
        this.HyperLink6.NavigateUrl += "&revision=yes";

        //this.Request.QueryString.Add("revision", "yes");

    }
}
